<?php
include_once '../AtacCommunicator/ACBusWaitingTimes.php';
include_once '../Exceptions/WrongParametersException.php';
include_once '../InfoManager/Constants.php';
include_once '../Utility/DebugLogs.php';
include_once '../Utility/RMobUtils.php';
include_once '../Model/BusSocialFeatures.php';
include_once '../Model/BusAtStop.php';


class PersistentBus extends BusAtStop implements XMLInterface{

	//Rappresenta a quale fermata siamo per il currentPathID
	private $currentStopPos;
	//Rappresenta la direzione che può essere ASC o DESC (ascendente, discendente)
	private $direction;
	//Rappresenta il tipo di autobus che può essere un fantasma, un notturno e un non monitorato
	private $type;

	function __construct($line,$bid=null,$referenceBusStop, $stopsLeft, $timeLeft, $currentPathID=null, $departureTime=null,$type=null)
	{
		if(!isset($bid)){
			parent::__construct($line,null,$referenceBusStop, $stopsLeft, $timeLeft, $currentPathID, $departureTime);
			$this->newPersistentBus();
			$this->setLineID($this->lineID);
		}else{
			if(!$this->retrievePersistentBusState($bid)) throw new Exception("Class: PersistentBus. Method: Constructor. \$bid parameter must be a valid vehicle id or null");
		}
	}

	public function toXML($mode) {
		$logfile = fopen($_SERVER['DOCUMENT_ROOT']."/RMob/iPhone-Server/Log/mycachelog.txt",'a');
				
		if (($this->currentPathID!=null) && ($this->currentPath==null))
		{
			$this->retrieveCurrentPath();
			
		}

		$xml = "";
		//compact mode: qui dentro non posso richiamare altri metodi toXML
		if ($mode==COMPACT_MODE) {
			$xml = "\n<BUSID>".$this->lineID."</BUSID>\n";
			$xml .= "\n<LINENUMBER>".$this->line->getLineNumber()."</LINENUMBER>\n";
			$xml = $xml."<TIMELEFT>".$this->timeLeft."</TIMELEFT>\n";
			$xml = $xml."<STOPSLEFT>".$this->stopsLeft."</STOPSLEFT>\n";
			if ($this->departureTime!=null)
				$xml = $xml."<DEPARTURETIME>".$this->departureTime."</DEPARTURETIME>\n"; 
			$xml = $xml."<PATHID>".$this->currentPathID."</PATHID>\n";
			$xml = $xml."<TYPE>".$this->type."</TYPE>\n";

			//echo "Linenumber:".$this->line->getLineNumber();
			//echo "PathID:".$this->currentPathID;
			
			//Prendo il current path e il suo id
			if($this->currentPathID == null){
				$this->retrieveCurrentPath();
				$pathID = $this->currentPath->getBusLinePathID();
			}else{
				$pathID = $this->currentPathID;
			}
			$stopID = $this->referenceStop->getAtacID();
			$this->updatePersistentBus($pathID,$stopID); 
			
			if ($this->currentPath != null)
			{
				$this->calcDirection();
				$xml = $xml."<START>".$this->currentPath->getStartPoint()->getStopName()."</START>\n";
				$xml = $xml."<STOPPOS>".$this->currentStopPos."</STOPPOS>\n";
				$xml = $xml."<DIRECTION>".$this->direction."</DIRECTION>\n";
				$xml = $xml."<END>".$this->currentPath->getFinalDestination()->getStopName()."</END>\n";
			}
		}
		
		//extended mode qui dentro posso chiamare solo metodi toXML in modalita compact
		if ($mode==EXTENDED_MODE) {
			$xml = "\n<LINENUMBER>".$this->line->getLineNumber()."</LINENUMBER>\n";
			$xml = $xml."<TIMELEFT>".$this->timeLeft."</TIMELEFT>\n";
			$xml = $xml."<STOPSLEFT>".$this->stopsLeft."</STOPSLEFT>\n";
			if ($this->departureTime!=null)
				$xml = $xml."<DEPARTURETIME>".$this->departureTime."</DEPARTURETIME>\n";
			$xml = $xml."<PATHID>".$this->currentPathID."</PATHID>\n";
			$xml = $xml."<TYPE>".$this->type."</TYPE>\n";

			if($this->currentPathID == null){
				$this->retrieveCurrentPath();
				$pathID = $this->currentPath->getBusLinePathID();
			}else{
				$pathID = $this->currentPathID;
			}
			$stopID = $this->referenceStop->getAtacID();
			//Il metodo updatePersistentBus si occupa anche di settare correttamente currentStopPos
			$this->updatePersistentBus($pathID,$stopID); 
			
			if ($this->currentPath != null)
			{
				$this->calcDirection();
				$xml = $xml."<START>".$this->currentPath->getStartPoint()->getStopName()."</START>\n";
				$xml = $xml."<STOPPOS>".$this->currentStopPos."</STOPPOS>\n";
				$xml = $xml."<DIRECTION>".$this->direction."</DIRECTION>\n";
				$xml = $xml."<END>".$this->currentPath->getFinalDestination()->getStopName()."</END>\n";
			}
				
			if ($this->currentPath!=null)
			{
				
				
				$xml.=$this->currentPath->toXML(COMPACT_MODE);
				/*
				foreach ($this->currentPath->getStops() as $busStop)
				{	
					$xml.=$busStop->toXML(COMPACT_MODE);
				}
				*/
			}
			
		}
		
		
		$xml = "\n".$this->elementStart."\n".$xml."\n".$this->elementEnd."\n"; 
		return $xml;
		
		
	}
	
	//Inserisce nel database un nuovo bus persistente nel tempo
	public function newPersistentBus(){
		$bid = getFirstDeadPersistentBus();
		calcDirection();
		if($this->currentPathID == null){
			$this->retrieveCurrentPath();
			$this->currentPathID = $this->currentPath->getBusLinePathID();
		}
		if($bid > 0){
			$query = "UPDATE ".PERSISTENTBUSTABLENAME."SET ".
				"line_num='".$this->line."',".
				"reference_bus_stop=".$this->referenceBusStop->getAtacID().",".
				"stops_left=".$this->stopsLeft.",".
				"timeLeft='".$this->timeLeft."',".
				"current_path_id=".$this->currentPathID.",".
				"departure_time='".$this->departureTime."',".
				"direction='".$this->direction."',".
				"isDead=0 WHERE bid=".$bid;
			$flag = 0;
		}else{
			$query = "INSERT INTO ".PERSISTENTBUSTABLENAME." ".
				"('".$this->line."',".$this->referenceBusStop->getAtacID().",".
				$this->stopsLeft.",'".$this->timeLeft."',".$this->currentPathID.",'".
				$this->departureTime."','".$this->direction."',0)";
			$flag = 1;
		}
		$conn = mysql_connect(DBHOST,DBUSER,DBPASS);
		if($conn == FALSE){
			return null;	
		}
		mysql_select_db(DBNAME);
		$result = mysql_query($query);
		if(!$result) return null;
		if($flag) $bid = mysql_insert_id(); //Ritorna l'ultimo id inserito
		$this->lineID = $bid;
	}
	//Recupera le informazioni presenti nella cache (DB) e popola i parametri del bus
	public function retrievePersistentBusState($bid){
		$conn = mysql_connect(DBHOST,DBUSER,DBPASS);
		if($conn == FALSE){
			return 0;	
		}
		mysql_select_db(DBNAME);
		$query = "SELECT * FROM ".PERSISTENTBUSTABLENAME." WHERE bid=".$bid;
		$result = mysql_query(RMobUtils::escape_var($bid));
		if(!$result) return 0;
		$bus = mysql_fetch_assoc($result);
		if(!$bus) return 0;
		$stop = new BusStop(null,$bus['reference_bus_stop']);
		parent::__construct($bus['line_num'],$bus['bid'],$stop, $bus['stops_left'], $bus['timeLeft'], $bus['current_path_id'], 			$bus['departure_time']);
		$this->setLineID($bid);
		return 1;	
	}
	//Aggiorna il record di un autobus persistente non morto alla fermata successiva in base alla direzione
	public function updatePersistentBus(){
		//Da definire ancora
	}	
	//Setta il record dell'autobus persistente per poter essere riutilizzato
	public function killPersistentBus(){
		$conn = mysql_connect(DBHOST,DBUSER,DBPASS);
		if($conn == FALSE) return null;
		mysql_select_db(DBNAME);
		$query = "UPDATE ".PERSISTENBUSTABLENAME." SET isDead=1 WHERE bid=".$this->lineID;
		$result = mysql_query($query);
		if(!$result) return null;
		$this->dropAllPersons();
	}
	//Ritorna il bus id del primo record di un autobus "morto" per poterci riscrivere sopra
	public function getFirstDeadPersistentBus(){
		$conn = mysql_connect(DBHOST,DBUSER,DBPASS);
		if($conn == FALSE) return null;
		mysql_select_db(DBNAME);
		$query = "SELECT bid FROM ".PERSISTENTBUSTABLENAME."WHERE isDead=1";
		$result = mysql_query($query);
		if(!$result) return -1;
		$row = mysql_fetch_assoc();
		if(isset($row['bid']))return $row['bid'];
		else return -1;
	}
	public function getCurrentStopPos(){
		return $this->currentStopPos;
	}
	public function setCurrentStopPos($pos){
		$this->currentStopPos = $pos;
		$this->updatePersistentBus(null,null);
	}
	public function getType(){
		return $this->type;
	}
	public function setType($type){
		if(!strcasecmp($type,GHOSTBUS) || !strcasecmp($type,NOTMONITOREDBUS) || !strcasecmp($type,NOCTURNBUS)){
			$this->type = $type;
		}
	}
	public function getDirection(){
		return $this->direction;
	}
	public function setDirection($direction){

		if(!strcasecmp($direction,"ASC") || !strcasecmp($direction,"DESC")){
			$this->direction = strtoupper($direction);
			$this->updatePersistentBus(null,null);
		}

	}
	public function calcDirection(){
		if($this->currentPath->getStartPoint()->getStopPos($pathID) == 1){
			$this->direction = "ASC";
		}
		else{
			$this->direction = "DESC";
		}
	}
}

?>
